// pages/register/register.js
var util = require('../../utils/util.js');
import api from '../../api/api.js'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: "",
    sms: "",
    pwd: "",
    repeatPwd: "",
    reg: 0,
    agreeReg: false,
    modal: {
      title: "注册协议",
      content: "众筹说明，众筹成功则按众筹价购买，退还众筹价与零售价的差价；",
      open: false,
    },
    v_text: "获取验证码",
    duration: 120,
    time: "",
    sending: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR;
        that.setData({
          winHeight: clientHeight
        });
      }
    });
  },
  onInput: function (e) {
    switch (e.target.dataset.name) {
      case "vendorName":
        this.setData({
          vendorName: util.trim(e.detail.value)
        });
        break;
      case "brandName":
        this.setData({
          brandName: util.trim(e.detail.value)
        });
        break;
      case "phone":
        this.setData({
          phone: util.trim(e.detail.value)
        });
        break;
      case "sms":
        this.setData({
          sms: util.trim(e.detail.value)
        });
        break;
      case "pwd":
        this.setData({
          pwd: util.trim(e.detail.value)
        });
        break;
      case "repeatPwd":
        this.setData({
          repeatPwd: util.trim(e.detail.value)
        });
        break;
    }
  },
  onRegister: function () {
    var self = this;
    var jsonStr = ""
    if (self.checkData()) {
      wx.showLoading({
        title: '请稍后...',
        mask: true
      })
      jsonStr = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"phone":"' + self.data.phone + '","code":"' + self.data.sms + '"}}'
      api.setSms({
        method: 'POST',
        data: { REQ_MESSAGE: jsonStr },
        complete: (res) => {
          wx.hideLoading()
          console.log(res);
          if (res.statusCode == 200) {
            if (res.data.REP_BODY.RSPCOD == "000000") {
              if (self.data.reg) {
                //厂商注册
                jsonStr = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"vendorName":"' + self.data.vendorName + '","brandName":"' + self.data.brandName + '","vendorPhone":"' + self.data.phone + '","passWord":"' + self.data.pwd + '","newPassWord":"' + self.data.repeatPwd + '","code":"' + self.data.sms + '"}}';
                api.register_1({
                  method: 'POST',
                  data: { REQ_MESSAGE: jsonStr },
                  complete: (res) => {
                    self.regSuccess(res)
                    wx.hideLoading();
                  },
                  fail: () => {
                    wx.hideLoading();
                  }
                })
              } else {
                //用户注册
                jsonStr = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"phone":"' + self.data.phone + '","sms":"' + self.data.sms + '","pwd":"' + self.data.pwd + '","repeatPwd":"' + self.data.repeatPwd + '"}}}';
                api.register_0({
                  method: 'POST',
                  data: { REQ_MESSAGE: jsonStr },
                  complete: (res) => {
                    // success
                    self.regSuccess(res)
                    wx.hideLoading();
                  },
                  fail: () => {
                    wx.hideLoading();
                  }
                })
              }
            } else {
              self.showModal(res.data.REP_BODY.RSPMSG)
            }
          } else {
            self.showModal("短信验证失败")
          }
        },
        fail: (res) => {
          wx.hideLoading()
          console.log("fail", res);
        }
      })
    }
  },
  regSuccess: function (res) {
    var that = this
    var jsonStr=""
    switch (res.statusCode) {
      case 200:
        if (res.data.REP_BODY.RSPCOD == "000000") {
          wx.showLoading({
            title: '正在登录...',
            mask: true
          })
          console.log("phone", that.data.phone)
          console.log("pwd", that.data.pwd)
          var json='{}';
          if (!that.data.reg) {
            jsonStr = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"phone":"' + that.data.phone + '","pwd":"' + that.data.pwd + '"}}';
            api.login({
              method: 'POST',
              data: { REQ_MESSAGE: jsonStr },
              complete: (res) => {
                // success
                wx.hideLoading();
                if (res.statusCode == 200) {
                  res.data.REP_BODY.LOGINTYPE = false;//用户登录
                  that.saveLogin(res.data)
                } else {
                  that.showModal("自动登录失败...")
                }
              },
              fail: () => {
                that.showModal("自动登录失败...")
              }
            })
          } else {
            jsonStr = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"vendor_phone":"' + that.data.phone + '","pass_word":"' + that.data.pwd + '"}}'
            //厂商登录
            api.businessLogin({
              method: 'POST',
              data: { REQ_MESSAGE: jsonStr },
              complete: (res) => {
                // success
                wx.hideLoading();
                if (res.statusCode == 200) {
                  res.data.REP_BODY.LOGINTYPE = true;//厂商登录
                  that.saveLogin(res.data)
                } else {
                  that.showModal("自动登录失败...")
                }
              },
              fail: () => {
                wx.hideLoading();
                wx.showModal({
                  title: '提示',
                  confirmColor: "#e30c26",
                  showCancel: false,
                  content: '登录失败'
                })
              }
            })
          }
        } else {
          that.showModal(res.data.REP_BODY.RSPMSG || res.data.REP_BODY.RSPCOD)
        }
        break;
      case 404:
        wx.showToast(api.status404)
        break;
      case 500:
        wx.showToast(api.status500)
        break;
      default:
        wx.showToast(res.data.REP_BODY.RSPCOD||"注册失败")
        break;
    }
  },
  //存储登录信息
  saveLogin: function (data){
    console.log("------",data)
    if (data.REP_BODY.RSPCOD == "000000") {
      //储存登录信息
      wx.setStorage({
        key: 'loginInfo',
        data: data,
        success: function () {
          wx.switchTab({
            url: '/pages/myPan/index/index',
          })
        }
      })
    } else {
      that.showModal(data.REP_BODY.RSPCOD)
    }
  },
  checkData: function () {
    var self = this
    if (self.data.reg) {
      if (util.trim(self.data.vendorName) == "" || !self.data.vendorName) {
        self.showModal("请输入公司名称")
        return false;
      }
      if (util.trim(self.data.brandName) == "" || !self.data.brandName) {
        self.showModal("请输入品牌名称")
        return false;
      }
    }
    if (util.trim(self.data.phone) == "" && self.data.phone.length == 11) {
      self.showModal("请输入手机号码")
      return false;
    }
    if (!util.check.phone(self.data.phone) || !self.data.phone) {
      self.showModal("请输入正确的手机号码")
      return false;
    }
    if (util.trim(self.data.sms) == "" || !self.data.sms) {
      self.showModal("请输入短信验证码")
      return false;
    }
    if (util.trim(self.data.pwd) == "" || !self.data.pwd) {
      self.showModal("请输入密码")
      return false;
    }
    if (util.trim(self.data.repeatPwd) == "" || !self.data.repeatPwd) {
      self.showModal("请输入重复密码")
      return false;
    }
    if (self.data.pwd < 6) {
      self.showModal("密码不能小于6位")
      return false;
    }
    if (util.trim(self.data.pwd) != util.trim(self.data.repeatPwd)) {
      self.showModal("两次密码不一致")
      return false;
    }
    if (!self.data.agreeReg) {
      self.showModal("您需要勾选阅读注册协议")
      return false;
    }
    return true;
  },
  showModal: function (text) {
    wx.showModal({
      title: '提示',
      content: text,
      showCancel: false,
      confirmColor: "#e30c26",
      success: function (res) {
      }
    })
  },
  sendSms: function () {
    var self = this
    console.log(self.data.sending)
    if (self.data.sending) return
    if (util.trim(self.data.phone) == "" && self.data.phone.length == 11) {
      self.showModal("请输入手机号码")
      return;
    }
    if (!util.check.phone(self.data.phone)) {
      self.showModal("请输入正确的手机号码")
      return;
    }
    var json = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"phone":"' + self.data.phone + '"}}'
    self.data.sending = true
    wx.showLoading({
      title: '请稍等...',
      mask:true
    })
    clearInterval(self.data.time)
    api.getSms({
      method: 'POST',
      data: { REQ_MESSAGE: json },
      complete: (res) => {
        wx.hideLoading()
        if (res.statusCode == 200) {
          if (res.data.REP_BODY.RSPCOD == "000000") {
            self.data.time = setInterval(function () {
              var text = ""
              if (self.data.duration > 0) {
                text = "重新发送(" + self.data.duration-- + ")"
              } else {
                text = "获取验证码"
                self.data.duration = 120;
                self.data.sending = false;
                clearInterval(self.data.time)
              }
              self.setData({
                v_text: text,
                duration: self.data.duration
              })
            }, 1000)
          } else {
            self.showModal(res.data.REP_BODY.RSPMSG)
            self.data.sending = false
          }
        } else {
          self.showModal("获取短信验证码失败")
          self.data.sending = false
        }
      },
      fail: (res) => {
        self.data.sending = false
        wx.hideLoading()
        self.showModal("获取短信验证码失败")
        console.log("fail", res);
      }
    })
  },
  regChange: function () {
    var that = this
    that.setData({
      reg: that.data.reg ? 0 : 1
    })
  },
  checkedFn: function () {
    var that = this
    that.setData({
      agreeReg: that.data.agreeReg ? false : true
    });
  },
  open_modal: function () {
    var that = this
    var modal = that.data.modal
    modal.open = true
    that.setData({
      modal: modal
    })
  },
  close_modal: function () {
    var that = this
    var modal = that.data.modal
    modal.open = false
    that.setData({
      modal: modal
    })
  },
  confirm_select: function () {
    this.close_modal();
    this.setData({
      agreeReg: true
    });
  }
})